package es.nadalgoyo.frikiquest.bbdd;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import es.nadalgoyo.frikiquest.bbdd.tablas.ListTablas;
import es.nadalgoyo.frikiquest.log.Log;
import es.sergionadal.mvc.bbdd.tablas.Tabla;

public class FrikiBBDD extends SQLiteOpenHelper {

	private List<Tabla> tablas;
	private ListTablas tablasList;

	public static String BBDD_NAME = "FrikiBBDD";

	public static int VERSION_BBDD = 1;

	public FrikiBBDD(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		tablasList = new ListTablas();
		tablas = tablasList.getAllTablas();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			for (Tabla tabla : tablas) {
				tabla.create(tablasList);
				db.execSQL(tabla.getSqlCreate());
			}
		} catch (SQLException e) {
			Log.e("Error creando las tablas de la BBDD: " + e.getMessage());
			e.printStackTrace();
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		for (Tabla tabla : tablas) {
			db.execSQL(tabla.getSqlDrop());
			db.execSQL(tabla.getSqlCreate());
		}
	}

	public ListTablas getTablasList() {
		return tablasList;
	}

	public static String getPathBBDD(Activity activity) {
		return activity.getApplication().getDatabasePath(BBDD_NAME)
				.getAbsolutePath();
	}

}
